<template>
  <div class="team-member-list">
    <div style="margin-bottom:12px;">
      <el-button type="primary" @click="openAddDialog">新增成员</el-button>
      <el-button @click="goBack">返回团队列表</el-button>
      <el-tag type="info" style="margin-left: 12px;">团队ID: {{ teamId }}</el-tag>
    </div>
    
    <!-- 团队成员列表 -->
    <el-table :data="memberList" stripe v-loading="loading" empty-text="暂无成员数据">
      <el-table-column prop="userName" label="成员名称" width="100" />
      <el-table-column prop="userAccount" label="用户名" width="150" />
      <el-table-column prop="teamName" label="所在部门" width="120" />
      <el-table-column prop="teamTypeName" label="岗位" width="100" />
      <el-table-column prop="userPhone" label="联系方式" width="150" />
      <el-table-column prop="roleName" label="角色" width="120" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary" text @click="openEditDialog(scope.row)">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button size="small" type="danger" text @click="confirmDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑 成员对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑成员' : '新增成员'" width="520px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="96px">
        <el-form-item label="选择用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户" style="width:100%" @change="onUserChange">
            <el-option v-for="user in userList" :key="user.id" :label="user.userName" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户账号" prop="userAccount">
          <el-input v-model="form.userAccount" placeholder="用户账号" readonly />
        </el-form-item>
        <el-form-item label="手机号" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="手机号" readonly />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="form.userEmail" placeholder="邮箱" readonly />
        </el-form-item>
        <el-form-item label="角色" prop="memberRole">
          <el-input v-model="form.memberRole" placeholder="请输入角色" />
        </el-form-item>
        <el-form-item label="状态" prop="memberStatus">
          <el-select v-model="form.memberStatus" placeholder="请选择状态" style="width:100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getReadClient, getWriteClient, Read } from '@/Urls/AxiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
// @ts-ignore
import { useCounterStore } from '@/stores/counter'

const router = useRouter()
const route = useRoute()

// 从路由参数获取 teamId
const teamId = ref<number>(Number(route.params.teamId) || 0)

const memberList = ref<any[]>([])
const userList = ref<any[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const formRef = ref()
const form = ref<any>({ memberStatus: 1 })

const rules = {
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  memberRole: [{ required: true, message: '请输入角色', trigger: 'blur' }],
  memberStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

// 获取用户列表（用于下拉选择）
const getUserList = async () => {
  try {
    const userread = getReadClient(4) // 使用主API服务器端口
    const res = await userread.get('sysread/api/Organize/GetUser')
    userList.value = res?.data?.data || []
  } catch(e) {
    console.error('GetUser 调用失败', e)
  }
}

// 获取团队成员列表
const fetchMemberList = async () => {
  try {
    loading.value = true
    console.log('正在获取团队ID为', teamId.value, '的成员列表')
    const teammenberread = getReadClient(1)
    const res = await teammenberread.get('schedread/api/Team/GetTeamMembers', {
      params: { teamId: teamId.value }
    })
    console.log('API响应:', res?.data)
    
    // 兼容不同的响应结构
    const data = res?.data?.data || res?.data
    memberList.value = Array.isArray(data) ? data : (data?.data || [])
    
    console.log('解析后的成员列表:', memberList.value)
    
    if (memberList.value.length === 0) {
      ElMessage.info('该团队暂无成员')
    }
  } catch (e) {
    console.error('GetTeamMembers 调用失败', e)
    ElMessage.error('获取团队成员失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (teamId.value) {
    fetchMemberList()
    getUserList()
  } else {
    ElMessage.error('团队ID无效')
    goBack()
  }
})

function goBack() {
  router.push('/Main/scheduling/team-list')
}

// 用户选择变化时的处理
function onUserChange(userId: number) {
  const selectedUser = userList.value.find((u: any) => u.id === userId)
  if (selectedUser) {
    form.value.userName = selectedUser.userName
    form.value.userAccount = selectedUser.userAccount
    form.value.userPhone = selectedUser.userPhone || ''
    form.value.userEmail = selectedUser.userEmail || ''
  }
}

function openAddDialog() {
  isEdit.value = false
  form.value = { memberStatus: 1, teamId: teamId.value }
  dialogVisible.value = true
}

function openEditDialog(row: any) {
  isEdit.value = true
  form.value = { ...row }
  // 如果已有用户ID，设置userId
  if (row.userId) {
    form.value.userId = row.userId
  }
  dialogVisible.value = true
}

async function submitForm() {
  try {
    // @ts-ignore
    await formRef.value?.validate()
    saving.value = true
    
    // 根据选择的用户ID获取用户信息
    const selectedUser = userList.value.find((u: any) => u.id === form.value.userId)
    if (!selectedUser) {
      ElMessage.error('请选择用户')
      return
    }
    
    // 根据API要求，只发送必要的字段
    const payload: any = {
      memberId: form.value.memberId,
      teamId: teamId.value,
      employeeId: form.value.userId, // 使用employeeId而不是userId
    }
    const teammenberwrite = getWriteClient(1)
    const store = useCounterStore()
    
    const config = { headers: { Authorization: 'Bearer ' + (store?.User?.Token || '') } }
    const res = isEdit.value
      ? await teammenberwrite.post('schedwrite/api/Team/UpdTeamMember', payload, config)
      : await teammenberwrite.post('schedwrite/api/Team/AddTeamMenber', payload, config)
    if (res?.data?.code === 200 || res?.data?.isSuccess) {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      fetchMemberList()
    } else {
      ElMessage.error(res?.data?.message || '提交失败')
    }
  } catch (e) {
    ElMessage.error('请求失败')
  } finally {
    saving.value = false
  }
}
const teammenberwrite = getWriteClient(1)
function confirmDelete(row: any) {
  ElMessageBox.confirm(`确认删除成员「${row.memberName}」吗？`, '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      saving.value = true
      const store = useCounterStore()
      const config = { headers: { Authorization: 'Bearer ' + (store?.User?.Token || '') } }
      const res = await teammenberwrite.post('schedwrite/api/Team/DelTeamMember', { memberId: row.memberId }, config)
      if (res?.data?.code === 200 || res?.data?.isSuccess) {
        ElMessage.success('删除成功')
        fetchMemberList()
      } else {
        ElMessage.error(res?.data?.message || '删除失败')
      }
    } finally {
      saving.value = false
    }
  }).catch(() => {})
}
</script>

<style scoped>
.team-member-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 16px;
}
</style>